define(function (require, exports, module) {
 
	var pageSize = 10;

	var $ = require('jquery');
	var layer=require('layer');
	require('jform');
	require('validate');

	layer.config({
		path: ctx+'/statics/pulgins/layer/'
	});

	/**
	 * 创建URL
	 */
	var createUrl = function (url, param) {
		var getUrl = '';
		if (url.indexOf('?') > 0) {
			getUrl = url + '&' + param;
		} else {
			getUrl = url + '?' + param;
		}
		return getUrl;
	};
  
	/**
	 * 创建可排序Table
	 * @param url 查询用URL
	 * @param tbl Table id
	 * @param tbody TBody ID
	 * @param tpl Tbody 模板
	 */
	var createSort = function (url, tbl, tbody, tpl, pageable, pageName, totalField) {
		var isPage = pageable || false;
		var $allCol = $("#" + tbl + " th[column]");
		$allCol.css('cursor', 'pointer');
		$allCol.addClass("sort_both");
		$allCol.unbind('click');
		// $("#" + tbl).unbind('click');
		// $("#" + tbl).on('click', 'th[column]', function() {
		$allCol.click(function () {
			if (typeof ($(this).attr('column')) == 'undefinded') return;
			var column = $(this).attr('column');
			$allCol.removeClass("sort_asc");
			$allCol.removeClass("sort_desc");
			$(this).removeClass("sort_both");

			$otherCol = $("#" + tbl + " th[column][column != '" + column + "']");
			$otherCol.attr('sortAsc', '');
			$otherCol.addClass("sort_both");
			var sort = 'sortKey=' + column;
			if ($(this).attr('sortAsc') == 'asc') {
				sort += '&sortAsc=2';
				$(this).attr('sortAsc', 'desc')
				$(this).addClass("sort_desc");
			} else {
				sort += '&sortAsc=1';
				$(this).attr('sortAsc', 'asc')
				$(this).addClass("sort_asc");
			}
			page(createUrl(url, sort), '#' + tbody, tpl, 1, isPage, pageName, totalField);
		});
		page(url, '#' + tbody, tpl, 1, isPage, pageName, totalField);
	};

	/**
	 * 分页查询
	 * @param url 查询用URL
	 * @param container TBody的Jquery ID
	 * @param tpl Tbody 模板
	 * @param curr 当前页码
	 */
	var page = function (url, container, tpl, curr, isPage, pageName, totalField) {
		if (!pageName) {
			pageName='page';
		}
		if (!totalField) {
			totalField = 'total';
		}
		curr = curr || 1;
		var template = require('template');
		var laypage = layui.laypage;//require('laypage');
		// laypage.dir = '/js/lib/laypage/skin/laypage.css';
		var getUrl;
		if (isPage) {
			if ($("select#pageSize").length > 0) {
				pageSize = $("select#pageSize").val();
				$("select#pageSize").unbind('change');
				$("select#pageSize").change(function() {
					page(url, container, tpl, 1, isPage, pageName);
				});
			}
		}
		getUrl = createUrl(url, 'pageSize='
			+ (isPage ? pageSize : 9999999)
			+ '&pageNum=' + (isPage ? curr : 1));

		//	getUrl += '&d=' + new Date();
		getDataAjax(getUrl, function (data) {
			$(container).html("");
			if (data.data.total > 0) {
				$(container).append(template(tpl, data.data));
			}
			$("span#" + totalField).text(data.data.total);
			layui.laypage({
				cont: pageName,
				pages: data.data.pages,
				skin: '#AF0000',
				curr: curr || 1,
				jump: function (obj, first) {
					if (!first) {
						page(url, container, tpl, obj.curr, isPage, pageName);
					}
				}
			});
		});
	};

	/**
	 * ajax取得数据
	 * @param url 查询用URL
	 * @param callback  回调函数
	 * @param error 出错处理函数
	 * @param aysnc 同步
	 * @param type http方法（POST GET）
	 */
	var getDataAjax = function (url, callback, error, aysnc, type) {
		if (aysnc == false) {
			aysnc = false;
		} else {
			aysnc = true;
		}

		if (!type) {
			type = "GET";
		}
		var layerIndex = layer.load();
		$.ajax({
			url: url,
			dataType: 'json',
			async: aysnc,
			cache: false,
			type: type,
			success: function (data) {
				layer.close(layerIndex);
				if (data.code == undefined) {
					if ($.isFunction(callback))
						callback(data);
				} else if (data.code == "0") {
					if ($.isFunction(callback))
						callback(data);
				} else {
					if ($.isFunction(error)) {
						error(data);
					} else {
						if (data.code != '4000004') {
							if (data.message)
								layer.msg(data.message);
						} else {
							layer.msg(data.message, function () {
								if (self != top) {
									window.parent.location.href = '/login';
								} else {
									window.location.href = '/login';
								}
							});
						}
					}
				}
			},
			error: function (a, b, c) {
				layer.close(layerIndex);
				alert(a.responseText);
			}
		});
	};

	/**
	 * ajax加载页面
	 * @param {*} url 
	 * @param {*} title 
	 */
	var loadPage = function (url, title) {
		var htmls = getHtmlPageAjax(url);
		$("section.content").html(htmls);
		$("title").text(title);
	};

	/**
	 * ajax获取html数据
	 * @param {*} url 页面URL
	 * @param {*} callback 成功回调
	 */
	var getHtmlPageAjax = function (url, callback) {
		var htmlData = null;
		var layerIndex = layer.load();
		$.ajax({
			url: url,
			dataType: 'html',
			async: false,
			success: function (data) {
				if (data.code && data.code != "0") {
					alert(data.message);
				} else {
					htmlData = data;
					if ($.isFunction(callback)) {
						callback();
					}
					layer.close(layerIndex);
				}
			},
			error: function (a, b, c) {
				layer.close(layerIndex);
				alert(a.responseText);
			}
		});
		return htmlData;
	};

	/**
	 * Alert对话框
	 * @param {*} content 内容
	 * @param {*} cbk 回调函数
	 */
	var alert = function (content, cbk) {
		layer.alert(content, function (index) {
			layer.close(index);
			if ($.isFunction(cbk)) {
				cbk();
			}
		});
	};

	/**
	 * 确认对话框
	 * @param {*} content 弹框内容
	 * @param {*} cbk 成功回调
	 */
	var confirm = function (content, cbk) {
		layer.confirm(content, function (index) {
			if (typeof (cbk) == 'function') {
				cbk();
			}
			layer.close(index);
		});
	};

	/**
	 * Layer弹窗页面
	 * @param {*} url 页面地址
	 * @param {*} title 弹窗Title
	 * @param {*} d 其他参数对象
	 */
	var showModelPage = function (url, title, d) {
		//  d == maxmin, width, height, btn, yes, success
		var htmls = getHtmlPageAjax(url + "?a=" + Math.random());
		if (htmls == null) return;
		var _w = d.width ? d.width : '600px';
		var _h = d.height ? d.height : '400px';
		var maxmin = d.maxmin || false;
		var full = d.full || false;
		var index = layer.open({
			type: 1,
			title: title,
			skin: 'layui-layer-demo', //加上边框
			area: [_w, _h], //宽高
			shift: 2,
			content: htmls,
			scrollbar: false,
			maxmin: maxmin,
			anim: 0,
			btn: d.btn || ['<i class="fa fa-save"></i> 保存', '<i class="fa fa-remove"></i> 取消'],
			success: function (layero, index) {
				if ($.isFunction(d.success)) {
					d.success(index);
				}
			},
			yes: function (index, layero) {
				if ($.isFunction(d.yes)) {
					d.yes(index);
				}
				//	layer.close(index);
			},
			btn2 : function(index, layero) {
				if ($.isFunction(d.btn2)) {
					return d.btn2(index);
				}
			}
		});
		if (full) {
			layer.full(index);
		}
	};

	/**
	 * Ajax 提交Form表单
	 * @param {*} id Form ID
	 * @param {*} url  Action URL
	 * @param {*} callback 成功回调
	 * @param {*} async 是否同步
	 */
	var submitForm = function (id, url, callback, async, errorCbk) {
		if (!async)
			async = true;
		var layerIndex = layer.load();
		$(id).ajaxSubmit({
			type: 'POST',
			// 			dataType : 'json',
			async: async,
			url: url,
			success: function (data) {
				layer.close(layerIndex);
				if (data.code == "0") {
					if ($.isFunction(callback))
						callback(data);
				} else if (data.code == '4000008') {
					var msg = data.message;
					for (var i = 0; i < data.data.length; i++) {
						var e = data.data[i];
						msg += '<br/>&nbsp;&nbsp;&nbsp;' + e.message;
					}
					// layer.alert(msg, { icon: 2 });
					layer.msg(msg);
					if ($.isFunction(errorCbk)) {
						errorCbk();
					}
				} else {
					layer.msg(data.message);
					if ($.isFunction(errorCbk)) {
						errorCbk();
					}
				}
			},
			error: function (a, b, c) {
				layer.close(layerIndex);
				alert(a.responseText);
			}
		});
	};

	/**
	 * form 验证
	 * @param {*} form Form ID
	 * @param {*} rules 验证规则
	 * @param {*} submitFunction 成功会提交函数
	 */	
	var formvalidate = function (form, rules, submitFunction) {
		$(form).validate({
			rules: rules,
			highlight: function (element) {
				$(element).closest('.form-group').addClass('has-error');
			},

			success: function (label) {
				label.closest('.form-group').removeClass('has-error');
				label.remove();
			},

			errorPlacement: function (error, element) {
				element.parent('div').append(error);
			},

			submitHandler: function (form) {
				if ($.isFunction(submitFunction))
					submitFunction();
			},
			errorElement: 'span',
			errorClass: 'help-block error-display',
			focusInvalid: false,
			ignore: "dsiabled"
		});
	};

	/**
	 * 初始化地域
	 * @param {*} id 
	 * @param {*} parentid 
	 */
	var initAreaSelect = function (id, parentid) {
		var $obj = $("#" + id);
		$obj.find('option').remove();
		var url = '';
		if (typeof ($obj.attr('area')) != 'undefined') {
			url = '/api/dict/area/list';
		} else if (typeof ($obj.attr('province')) != 'undefined') {
			url = '/api/dict/province/list?area=';
			if (parentid) {
				url += parentid;
			}
		} else if (typeof ($obj.attr('city')) != 'undefined') {
			url = '/api/dict/city/list?province=';
			if (parentid) {
				url += parentid;
			}
		}
		if (url == "") return;

		getDataAjax(url, function (data) {
			var $obj = $("#" + id);
			var selectedValue = $obj.attr("selectedValue");
			for (var i = 0; i < data.data.length; i++) {
				var d = data.data[i];
				if (selectedValue != '' && selectedValue == d.value) {
					$obj.append('<option value="' + getValue(d.value) + '" selected>' + d.label + '</option>');
				} else {
					$obj.append('<option value="' + getValue(d.value) + '">' + d.label + '</option>');
				}
			}
		}, null, false);
	}

	/**
	 * 初始化字典下拉框
	 */
	var initDictSelect = function (display) {
		$("select[dict]").each(function () {
			if ($(this).children().length <= 0){
			var id = $(this).attr("id");
			$(this).find('option').remove();
			var dict = $(this).attr('dict');
			var url = '/api/dict/list?dictName=' + dict;
			// 角色列表
			if (dict == 'role') {
				url = '/api/dict/role';
			}
			getDataAjax(url, function (data) {
				var $obj = $("#" + id);
				var selectedValue = $obj.attr("selectedValue");
				for (var i = 0; i < data.data.length; i++) {
					var d = data.data[i];
					if (!display) {
						if (selectedValue != '' && selectedValue == d.value) {
							$obj.append('<option value="' + getValue(d.value) + '" selected>' + d.label + '</option>');
						} else {
							$obj.append('<option value="' + getValue(d.value) + '">' + d.label + '</option>');
						}
					} else {
						if(i != 0) {
							$obj.append('<option value="' + getValue(d.value) + '">' + d.label + '</option>');
						}
					}
					
				}
			}, null, false);
			}
		});
		
	};

	var getValue = function (v) {
		return v == null ? '' : v;
	}

	/**
	 * ajax Post提交json内容
	 * @param {*} url post地址
	 * @param {*} option 数据内容
	 * @param {*} callback 成功回调
	 */
	var ajaxJson = function (url, option, callback) {

		var layerIndex = layer.load();
		$.ajax(url, {
			type: 'post',
			dataType: 'json',
			data: option,
			success: function (data) {
				layer.close(layerIndex);
				if (data.code == "0") {
					if ($.isFunction(callback))
						callback(data);
				} else if (data.code == '4000008') {
					var msg = data.message;
					for (var i = 0; i < data.data.length; i++) {
						var e = data.data[i];
						msg += '<br/>&nbsp;&nbsp;&nbsp;' + e.message;
					}
					layer.msg(msg);
					// layer.alert(msg, { icon: 2 });
					// layer.msg(data.message);
				} else {
					layer.msg(data.message);
				}
			},
			error: function (response, textStatus, errorThrown) {
				try {
					layer.close(layerIndex);
					alert(a.responseText);
				} catch (e) {
					alert('提示', "请求出现异常,请联系管理员.", 4);
				}
			},
			complete: function () {
			}
		});
	};

	/**
	 * 文件上传
	 * @param {*} url 	上传路径
	 * @param {*} file  文件控件name
	 * @param {*} btn   上传按钮
	 * @param {*} cbk   回掉函数
	 */
	var upload = function (url, file, btn, cbk) {
		var $upload = require('upload');
		new AjaxUpload($("#" + btn), {
			action: url,
			name: file,
			responseType: 'json',
			onSubmit: function (file, ext) {
				if (!(ext && /^(png|PNG|jpg|jpeg|JPG|JPEG)$/.test(ext))) {
					alert('文件格式不正确,请选择 jpg 格式的文件!');
					return false;
				}
				this.disable();
			},
			onComplete: function (file, d) {
				this.enable();
				if (d && d.code && d.code != '0') {
					layer.msg(d.msg);
					return;
				}
				if ($.isFunction(cbk)) {
					cbk(d);
				}
			}
		});
	};

	/**
	 * 右下角弹窗
	 * @param {*} content 弹窗内容
	 * @param {*} p 
	 */
	var showTip = function(content, p) {
		layer.open({
			type : 1,
			offset : 'rb',
			content : content,
			shade : 0,
			title : false,
			closeBtn : 0
		})
	}


	// 类型
	// mark_type = ["area", "provicne"]
	var setAreaProvinceCity = function(area_id, province_id, city_id, mark_type) {

		// area_id, province_id, city_id, mark_type,必须全部传入
		if (mark_type === "area") {

			$(province_id).empty();
			var area_value = $(area_id).val();
			if (area_value == '') {
				$(city_id).empty();
				$(province_id).append('<option>省</option>');
				$(city_id).append('<option>市</option>');
				return;
			}
			
			var url = "/api/dict/province/list?area=" + $(area_id).val();
			getDataAjax(url, function(data){

				var d= data.data;
				var v = null;
				for (var i = 0; i < d.length; ++i) {
					v = d[i].value == null ? '' : d[i].value;
					if (v == null) {
						$(province_id).append('<option value="">' + d[i].label + '</option>');
					}
					$(province_id).append('<option value="' + v + '">' + d[i].label + '</option>');
				}
			}, null, false);

		}

		if (mark_type === "province") {

			$(city_id).empty();
			var provicne_value = $(province_id).val();
			if (provicne_value == '') {
				$(city_id).append('<option>市</option>');
				return;
			}
			
 			var url = "/api/dict/city/list?province=" + $(province_id).val();
			getDataAjax(url, function(data){

				var d= data.data;
				var v = null;
				for (var i = 0; i < d.length; ++i) {
					v = d[i].value == null ? '' : d[i].value;
					if (v == null) {
						$(city_id).append('<option value="">' + d[i].label + '</option>');
					}
					$(city_id).append('<option value="' + v + '">' + d[i].label + '</option>');
				}
			}, null, false);

		}
	};

	var addImage = function(url, fileId) {
		return "<div class='pull-left img-div'><img src='"
                + url
                + "' id='"+fileId +"' style='height:100px'/>"
                + "<div><i class='fa fa-close'></i></div></div>";
	}

	var showImage = function(url) {
		var maxWidth = document.body.offsetWidth - 10;
		var maxHeight = document.body.offsetHeight - 40;

		var padding = 10;
		layer.open({
			type: 1,
			title: false,
			area: [ 'auto', maxHeight + 'px'],
			skin: 'layui-layer-nobg', //没有背景色
			shadeClose: true,
			content: "<img src='" + url + "' id='layer-img-00001' style='height:" + (maxHeight) + "px'/>",
			success : function(layero, index) {
				var $img = $("#layer-img-00001");
				var oldWidth = $img.width();
				var oldHeight = $img.height();
				if (oldWidth > maxWidth - padding) {
					$img.width(maxWidth - padding);
				}
				if (oldHeight > maxHeight - padding) {
					$img.height(maxHeight - padding);
				}
			}		
		});
	}

	var createRichedit = function(id, o) {
		var layedit = layui.layedit;
		var index = layedit.build(id, {
			height : o.height || 280,
            tool: ['strong', 'italic', 'underline', '|', 'left', 'center', 'right', '|', 'face', 'image'],
			uploadImage : o.uploadImage || {}
		});
		return index;
	};

	var getDateStr = function (date, days) {
		var d = new Date(date);
		d.setDate(d.getDate() + days);
		var month = d.getMonth() + 1;
		var day = d.getDate();
		if (month < 10) {
			month = "0" + month;
		}
		if (day < 10) {
			day = "0" + day;
		}
		var val = d.getFullYear() + "-" + month + "-" + day;
		return val;
	}

	/**
	 * 格式化金额
	 * （小数点后的数字不做处理，没有小数的情况默认在数字末尾追加".00")
	 * 例如input->12345; output-> 12,345.00
	 * 
	 * @param {*} amount 金额
	 */
	var formatAmount = function(amount){
			if(typeof(amount) == "undefined" || amount == ""){
            	return "0.00";
        	}

        	if(amount.toString().indexOf(".") == -1){
        		amount += ".00";
        	}

	        var amountArray = amount.toString().split(".");
			var formattedAmount = "0.00";

	        if(amountArray.length > 1){
	        	var intPart = amountArray[0];

	        	if(intPart.length <= 3){
	        		return intPart + "." + amountArray[1];
	        	}

	        	var charSize = intPart.length;
	        	var commaQty = charSize % 3 == 0 ? Math.floor(charSize/3) - 1 : Math.floor(charSize/3);

	        	var commaGroup = new Array();
	        	for(var i = 0; i < commaQty + 1; i++){
	        		if(charSize - 3*(i+1) > 0 ){
						commaGroup.push(intPart.substring(charSize - 3*(i+1), charSize - 3*i));
	        		}else{
	        			commaGroup.push(intPart.substring(0, charSize - 3*i));
	        		}
	        	}

				//小数1位的情况下，末位补0
				if(amountArray[1].length == 1){
					amountArray[1] += "0";
				}

	        	formattedAmount = commaGroup.reverse().join(",") + "." + amountArray[1];
	        }

			return formattedAmount;
	}

    return {
        loadPage: loadPage,
        submitForm : submitForm,
        getDataAjax : getDataAjax,
		page : page,
		alert : alert,
		confirm : confirm,
		showModelPage : showModelPage,
		formvalidate : formvalidate,
		createUrl : createUrl,
		createSort : createSort,
		initDictSelect : initDictSelect,
		initAreaSelect : initAreaSelect,
		ajaxJson : ajaxJson,
		setAreaProvinceCity : setAreaProvinceCity,
		upload : upload,
		createRichedit : createRichedit,
		addImage : addImage,
		showImage : showImage,
		getDateStr : getDateStr,
		formatAmount: formatAmount
    }
});